package com.gz.controller;

import com.gz.common.RedisConst;
import com.gz.entity.Address;
import com.gz.entity.Vo.AddressVo;
import com.gz.exception.SystemCode;
import com.gz.service.AddressService;
import com.gz.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/address")
//@Api(tags = "购物车接口")
@Slf4j
public class AddressController {

    @Autowired
    AddressService addressService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;  //要实现会话跟踪，从Token中获取用户id

    @GetMapping("/getAddressByUid/{id}")
    public ResponseEntity<?> getAddressByUid(@PathVariable Long id) {
        ValueOperations<String, List<AddressVo>> ops = redisTemplate.opsForValue();
        List<AddressVo> addresses = ops.get(RedisConst.USER_ADDRESS + ":" + id);
        List<AddressVo> addressVos = new ArrayList<>();
        if (addresses != null && addresses.size() > 0) {
            return ResponseEntity.ok(addresses);
        }else {
            addressVos = addressService.updateAddressCache(id);
        }
        return ResponseEntity.ok(addressVos);
    }

    @PostMapping("/addAddress")
    public ResponseEntity<?> addAddress(@RequestBody Address address) {
        addressService.addAddress(address);
        return ResponseEntity.ok(SystemCode.SUCCESS_ADD_ADDRESS.getMessage());
    }
}